package com.gzh.system.service.timetask;

import com.google.common.collect.Lists;
import com.gzh.core.dao.mapper.WorkMapper;
import com.gzh.core.dao.po.WorkEntity;
import com.gzh.core.util.NumericHelper;
import com.gzh.core.util.StringUtils;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Condition;

import java.util.List;

/**
 * @Author guanzh
 * @Date 2021/12/2 15:50
 * @Description
 */
@Component
@Slf4j
public class AutoStartWorkTask {
    @Autowired
    private WorkMapper workMapper;

    //自动发布作业
    @XxlJob(value = "autoStartWorkTask")
    public ReturnT<String> autoStartWorkTask(String param) {
        try {
            log.info("调用自动发布作业定时任务开始");
            Integer date = NumericHelper.toInteger(StringUtils.formatDate());
            Integer time = NumericHelper.toInteger(StringUtils.formatTime());
            Condition workCondition = new Condition(WorkEntity.class);
            workCondition.createCriteria().andEqualTo("isPublish",0);
            List<WorkEntity> workEntityList = workMapper.selectByCondition(workCondition);
            List<Integer> updateIdList = Lists.newArrayList();
            for (WorkEntity workEntity : workEntityList) {
                Integer publishDate = workEntity.getPublishDate();
                Integer publishTime = workEntity.getPublishTime();
                if ((publishDate == null || publishDate == 0) || (publishTime == null || publishTime == 0)){
                    continue;
                }
                if (date > publishDate || (date.equals(publishDate) && time >= publishTime)){
                    updateIdList.add(workEntity.getWorkId());
                }
            }
            if (!CollectionUtils.isEmpty(updateIdList)){
                Condition condition = new Condition(WorkEntity.class);
                condition.createCriteria().andIn("workId",updateIdList);
                WorkEntity workEntity = new WorkEntity();
                workEntity.setIsPublish(1);
                workMapper.updateByConditionSelective(workEntity,condition);
            }
            log.info("调用自动发布作业定时任务结束");
        } catch (Exception e) {
            log.error("调用定时任务错误：自动发布作业", e);
            return ReturnT.FAIL;
        }
        return ReturnT.SUCCESS;
    }
}
